# -*- coding: utf-8 -*-
from odoo import models, fields, api, tools, _
import datetime, time

class AutoTask(models.AbstractModel):
    _name="tyibs.main.auto.task"

    @api.model
    def generate_due_not_main_order(self):

        """
        生成超期未维保工单
        :return:
        """
        current_date_str = time.strftime('%Y-%m-%d',time.localtime(time.time()))
        main_cycle = self.env.ref("lift_main.tyibs_main_maintenance_cycle").cycle
        deadline = (datetime.datetime.now() + datetime.timedelta(days=-main_cycle)).strftime("%Y-%m-%d")
        due_lift_ids = self.env["tyibs.base.lift"].search([('last_maintenance_date', '<', deadline)])
        for item in due_lift_ids:
            # 最后一次工单
            last_order = self.env["tyibs.main.work.order"].search([("lift_id", "=", item.id)], order="maintenance_end_time desc", limit=1)
            # 最后一次维保时间(包含超期未维保)
            last_order_date_str = last_order.maintenance_end_time[0:10]
            last_order_date = datetime.datetime.strptime(last_order_date_str, "%Y-%m-%d")
            current_date = datetime.datetime.strptime(current_date_str, "%Y-%m-%d")
            # 最后一次维保工单的时间和当前时间的差值
            diff_date = (current_date - last_order_date).days

            # 根据差值计算应该有多少条超期维保工单
            for i in xrange(diff_date/main_cycle - 1):
                last_order_date += datetime.timedelta(days=main_cycle)
                order_vals = {
                    "use_company_id": item.use_company_id.id,
                    "lift_id": item.id,
                    "main_company_id": item.maintenance_company_id.id,
                    "employee_ids": [(6, False, item.main_dis_list_ids.employee_ids.ids)],
                    "maintenance_start_time": last_order_date,
                    "maintenance_end_time": last_order_date,
                    "category": 15,
                    "order_state": 3,
                    "sign_in_date": last_order_date,
                    "over_due_state": "over_due_not_main"
                }
                self.env["tyibs.main.work.order"].origin_create(order_vals)

